# added by yinchao, Fri June 28 10:33	2024

from keyword import iskeyword
import socket
import re

default = 'http://data.pr4e.org/romeo.txt'
address = input(f'Enter an address(default {default}): ')
if address == '':
    address = default

# 补全反斜线
# if address[-1] != '/':
#     address += '/'

hostname = re.search('http[s]?://(.+?)/', address).groups()
if len(hostname) == 0:
    exit()
# print(hostname) # 只有一个元素也是 tuple
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysocket.connect((hostname[0], 80))
cmd = f'GET {address} HTTP/1.0\r\n\r\n'
cmd = cmd.encode(encoding='ascii')

mysocket.sendall(cmd)

content = b''
while True:
    data = mysocket.recv(1024)
    if len(data) == 0:
        break

    content += data

content = content.decode()
# print(content)
# print(content.split('\r\n\r\n'), len(content.split('\r\n\r\n')))
header, body = content.split('\r\n\r\n')
# print(header)
# print(body)
print(body.strip())

# zfill, casefold, partition, ljust, isidentifier, format,
# zfill, zero fill for string in the left.
name = 'yinchao'
print(name.zfill(10))  # 000yinchao
# casefold, 与 lowercass 相比, 会将字符串中无法转大小写的字符转换, 如德语的 ß 转为 ss
print('ß'.casefold())
print('中'.casefold())  # ???
# partition, https://docs.python.org/3/library/stdtypes.html#str.partition, 分割字符串(before, sep, after), 使用 split 替代.
name = 'yin-chao'
print(name.partition('-'))  # ('yin', '-', 'chao')
# ljust, https://docs.python.org/3/library/stdtypes.html#str.ljust, 填充字符宽度, string left justified, 填充在右侧
print(name.ljust(10, '-'))  # yin-chao--
# isidentifier, https://docs.python.org/3/library/stdtypes.html#str.isidentifier 是否是一个合法的标识符, vs iskeyword
print(iskeyword('from'))  # true
print(iskeyword('hello'))  # false
print(iskeyword('def'))  # True
print('hello'.isidentifier())  # true
print('1'.isidentifier())  # false
print('h1'.isidentifier())  # true
print('class'.isidentifier())  # false?? true
# format, perform a string formatting operation.
# the string on which this method is called can contain literal text or replacement fields delimited by braces {}.
# each replacement field contains either the numberic index of a positional argument, or the name of a keyword argument.
# Retruns a copy of the string where each replacement field replaced with the string value of the corresponding argument.
# format string syntax , https://docs.python.org/3/library/string.html#formatstrings
print('{name}, {2}'.format(name, '1995'))
